<template>
    <div style="position: relative;">
        <div class="btn" @click="change('left')" style="left: 20px;">&lt;
        </div>
        <div class="btn" @click="change('right')" style="right: 10px;">&gt;
        </div>
        <div ref="chart5" style="height: 340px;">

        </div>
        <div style="color: #fff; position: absolute;right:20px;bottom:20px;">{{ name }}</div>
    </div>
</template>

<script setup lang="ts">
import axios from "axios";
import * as echarts from "echarts";
import type { EChartsOption } from 'echarts/types/dist/echarts.d.ts'
import { onMounted, ref } from "vue";

let option: EChartsOption = {
    tooltip: {
        show: true,
        formatter: function (item: any) {
            let str = ``
            item.data.children.forEach((it: any) => {
                str += `${it.name}:${(it.value * 100 / item.value).toFixed(0)}%<br>`
            })
            return str
        },
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        textStyle: {
            color: '#fff'
        },
        borderColor: "transparent"
    },
    legend: {
        top: 25,
        orient: 'horizontal',
        textStyle: {
            fontSize: 8,
            color: '#ccc'
        },
        icon: 'circle',

    },
    series: [
        {
            name: '',
            type: 'pie',
            radius: '50%',
            data: [],
            label: {
                show: false
            },
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                },

            },
            center: ['50%', '55%'],
        }
    ],
}

let chart5 = ref<HTMLDivElement | null>(null)
let myECharts: echarts.ECharts | null = null


let totalData: any = []
let name = ref<string>('')
function init() {
    myECharts = echarts.init(chart5.value)
    axios.get("/api/hot.json").then(({ data }) => {
        // console.log(data);
        totalData = data;
        (option.series as any[])[0].data = totalData?.[0].children;
        (option.series as any[])[0].name = totalData?.[0].name;
        name.value = totalData?.[0].name;
        myECharts?.setOption(option)
    })
}

let k = 0
function change(direction: "left" | 'right') {
    console.log(k);

    if (direction == "left") {
        k <= 0 ? k = 2 : k--
    } else {
        k >= 2 ? k = 0 : k++
    }
    (option.series as any[])[0].name = totalData?.[k].name;
    (option.series as any[])[0].data = totalData?.[k].children;
    name.value = totalData?.[k].name;

    myECharts?.setOption(option)
}

onMounted(() => {
    init()
    window.addEventListener('resize', () => { myECharts?.resize() });
})
</script>

<style scoped>
.btn {
    position: absolute;
    color: #fff;
    top: 50%;
    z-index: 10;
    width: 30px;
    height: 30px;
}

.btn:hover {
    cursor: pointer;
}
</style>